// pages/matching/matching.js
const qcloud = require('../../vendor/qcloud-weapp-client-sdk/index.js')
const config = require('../../config.js')
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    matchingTime: 1,
    matchingInter: '',
    ws:'',
    matchingState:false,
    token:'',
    playState:false,
    exitState:'',
    animationData:{},
  },

  // /sensitive/exam/obtainMatchToken

  onShow() {
    var animation = wx.createAnimation({
      duration: 20000,
      timingFunction: 'ease',
      transformOrigin: 'left top 0'
    })

    
    this.animation = animation

    animation.translateX(-3600).step()
    animation.translateX(0).step()
    
    this.setData({
      animationData: animation.export()
    })

  },

  getobtainMatchToken() {
    return new Promise((resolve, reject)=>{
      qcloud.request({
        url: config.service.obtainMatchToken,
        method: "POST",
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        login: true,
        data: {
          'uId': app.globalData.uId,
          'epId': app.globalData.epId
        },
        success: (response) => {
          resolve(response.data.token)
          
        },
        fail: (err) => {
          reject(err)
        }
      });
    })

    
  },

  // 页面离开
  onHide: function () {
    clearInterval(this.data.matchingInter)
    this.setData({
      matchingTime:1
    })
    if (this.data.exitState !== 'start') {
      wx.closeSocket((res) => {
        console.log('WebSocket 已关闭！')
      })
      
      wx.navigateBack({})
    }

    // var clearAnimation = wx.createAnimation({ duration: 0 });
    // clearAnimation.translateX(0).step()
    // this.setData({ animation: clearAnimation.export() })
  },

  onUnload:function() {
    clearInterval(this.data.matchingInter)
    this.setData({
      matchingTime:1
    })
    if (this.data.exitState !== 'start') {
      wx.closeSocket((res) => {
        console.log('WebSocket 已关闭！')
      })

      // wx.redirectTo({
      //   url: `/pages/index/index`
      // })
    }

    // var clearAnimation = wx.createAnimation({ duration: 0 });
    // clearAnimation.translateX(0).step()
    // this.setData({ animationData: clearAnimation.export() })
  },


  websocketFn(token) {
    // 链接成功
    wx.connectSocket({
      url: config.service.match
    })

    wx.onSocketOpen((res) => {
      // 发送token 请求对战
      wx.sendSocketMessage({
        data: JSON.stringify({
          "action": "request_match",
          "matchToken": token
        })
      })
    })

    // 接收服务器返回信息
    wx.onSocketMessage((data) => {
      var data = JSON.parse(data.data)
      // 返回对战id，告知是否发起者还是应答着
      if (data.action == 'request_match_rsp') {
        this.request_match_rsp(data)
      }

      // 人机模式应答(加入)
      if (data.action == 'battle_machine_mode_rsp') {
        this.battle_machine_mode_rsp()
        
      }
    

      // 应战者加入
      if (data.action == 'start_battle_man') {
        // 请求试卷信息和选手信息
        this.start_battle_man()
        // 状态（是否人机，还是真人pk)
        app.globalData.matchType = 'reality'
      }

      // 返回试卷信息和选手信息
      if (data.action == 'request_player_info_and_paper_rsp') {
        // 发起者信息
        app.globalData.ownInfo = data.data.ownInfo
        // 应战者信息
        app.globalData.opponentInfo = data.data.opponentInfo
        //试卷信息
        app.globalData.paperDTO = data.data.paperDTO
        //答案信息
        app.globalData.questionDTOs = data.data.questionDTOs
        this.setData({
          playState:true
        })
        
        this.setData({
          exitState:'start'
        })


        wx.redirectTo({
          url: `/pages/vsAnimation/vsAnimation`
        })
      }
    })

    // 关闭websocket
    // wx.onSocketClose(function (res) {
    //   console.log('WebSocket 已关闭！')
    // })

    //监听关闭
    // wx.onSocketClose(function (res) {
    //   console.log('WebSocket 已关闭！')
    // })
  },

  // 人机模式开始->请求试卷
  battle_machine_mode_rsp() {
    wx.sendSocketMessage({
      data: JSON.stringify({
        "action": "request_player_info_and_paper",
      })
    })
  },
  //向发送人机模式
  manMachine() {
    wx.sendSocketMessage({
      data: JSON.stringify({
        "action": "battle_machine_mode",
      })
    })
  },
  //应战者加入，请求选手信息和试卷
  start_battle_man() {
    clearInterval(this.data.matchingInter)
    wx.sendSocketMessage({
      data: JSON.stringify({
        "action": "request_player_info_and_paper",
      })
    })
  },
  //请求对战
  request_match_rsp(data) {
    //存储对战id
    app.globalData.emId = data.emId
    

    // 判断对站者还是应战者
    if (data.matchType == 'new') {

      //创建对战者
      this.matchingFn().then((value) => {
        if (value == true) {
          wx.sendSocketMessage({
            data: JSON.stringify({
              "action": "battle_machine_mode",
            })
          })
        }
      })
    } else {
      // 应战者
      this.setData({
        matchingState: true
      })
      
      // 状态（是否人机，还是真人pk)
      app.globalData.matchType = 'reality'

      // 应战者加入，立即获取试卷
      wx.sendSocketMessage({
        data: JSON.stringify({
          "action": "request_player_info_and_paper",
        })
      })
    }
  },

  matchingFn() {
    return new Promise((resolve, reject) => {
      clearInterval(this.data.matchingInter)
      this.data.matchingInter = setInterval(() => {
        if (this.data.matchingTime >= 15) {
          clearInterval(this.data.matchingInter)
          this.setData({
            matchingState: true
          })
          app.globalData.matchType = 'machine'
          resolve(true)
        } else {
          this.setData({
            matchingTime: this.data.matchingTime + 1
          })
        }
      }, 1000)

    })
    
  },

  onReady: function () {
    this.getobtainMatchToken().then((value)=>{
      this.setData({
        token: value
      })

      this.websocketFn(this.data.token)
    })

    // 检测断线状态
    wx.onSocketMessage((data) => {
      var data = JSON.parse(data.data)
      if (data.action == 'opponent_disconnect') {
        wx.closeSocket((res) => {
          console.log('WebSocket 已关闭！')
        })

        wx.redirectTo({
          url: `/pages/officialExplain/officialExplain`
        })
      }
    })

  } 
})